package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.fegin.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParams;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Attr;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yyy
 * @Date 2020-06-28 19:14
 * @Email yangyouyuhd@163.com
 * @Note
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ProductFeignService productFeignService;

    @Override
    public SearchResult searchParams(SearchParams params) {
        //检索请求 GET product/_search
        SearchRequest searchRequest = new SearchRequest(EsConstant.PRODUCT_INDEX);

        //根据参数构建检索器
        SearchSourceBuilder searchSourceBuilder = searchRequestBuilder(params);

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            //执行结果请求
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 结果处理
        SearchResult searchResult = searchResultHandler(searchResponse, params);
        return searchResult;
    }


    /**
     * 根据参数集合、构建一个检索资源构建器
     *
     * @param params
     * @return
     */
    private SearchSourceBuilder searchRequestBuilder(SearchParams params) {
        //组装到搜索资源构建器
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //检索关键字构建
        if (StringUtils.isNotEmpty(params.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery(EsConstant.SKU_TITLE, params.getKeyword()));
        }
        //商品分类构建、term
        if (ObjectUtils.isNotEmpty(params.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery(EsConstant.CATALOG_ID, params.getCatalog3Id()));
        }
        //商品Id集合构建、terms
        if (ObjectUtils.isNotEmpty(params.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery(EsConstant.BRAND_ID, params.getBrandId()));
        }

        //如果还限制了很多属性、内嵌的
        if (ObjectUtils.isNotEmpty(params.getAttrs())) {
            for (String attr : params.getAttrs()) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                String[] a = attr.split("_");
                String[] attrValues = a[1].split(":");

                boolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrId", a[0]));
                boolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));


                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs",boolQueryBuilder, ScoreMode.None);
                boolQuery.filter(nestedQueryBuilder);
            }
        }

        //只看有库存
        if (ObjectUtils.isNotEmpty(params.getHasStock())) {
            boolQuery.filter(QueryBuilders.termsQuery(EsConstant.HAS_STOCK, params.getHasStock() == 1));
        }
        //价格查询拼装
        if (StringUtils.isNotEmpty(params.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(EsConstant.SKU_PRICE);
            String[] prices = params.getSkuPrice().split("_");
            //对价格区间组装查询
            if (params.getSkuPrice().startsWith("_")) {
                rangeQuery.lte(prices[0]);
            } else if (params.getSkuPrice().endsWith("_")) {
                rangeQuery.gte(prices[0]);
            } else {
                rangeQuery.gte(prices[0]).lte(prices[1]);
            }
            boolQuery.filter(rangeQuery);
        }


        builder.query(boolQuery);

        /**
         * 排序，分页
         */
        //排序构建
        if (StringUtils.isNotEmpty(params.getSort())) {
            String[] s = params.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], order);
        }
        //分页
        builder.from(((params.getPageNum() == null ? 1 : params.getPageNum())  - 1) * EsConstant.pageSize);
        builder.size(EsConstant.pageSize);
        //高亮
        if (StringUtils.isNotEmpty(params.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field(EsConstant.SKU_TITLE);
            highlightBuilder.preTags("<em style='color:red'>");
            highlightBuilder.postTags("</em>");
            builder.highlighter(highlightBuilder);
        }

        // 聚合检索构建
        builder = aggregationRequestBuilder(builder);

        System.out.println("搜索条件：" + builder.toString());
        return builder;
    }

    /**
     * 根据参数集合、构建一个聚合检索构建器
     *
     * @param
     * @return
     */
    private SearchSourceBuilder aggregationRequestBuilder(SearchSourceBuilder builder) {
        /**
         * 构建品牌聚合、和其2个子聚合
         */
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field(EsConstant.BRAND_ID).size(EsConstant.pageSize);
        brandAgg.subAggregation(AggregationBuilders
                .terms("brand_name_agg")
                .field(EsConstant.BRAND_NAME)
                .size(1)
        ).subAggregation(AggregationBuilders
                .terms("brand_Img_agg")
                .field(EsConstant.BRAND_IMG)
                .size(1)
        );
        builder.aggregation(brandAgg);

        //分类聚合catalog_name_agg
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field(EsConstant.CATALOG_ID).size(EsConstant.pageSize);
        catalogAgg.subAggregation(AggregationBuilders
                .terms("catalog_name_agg")
                .field(EsConstant.CATALOG_NAME)
                .size(EsConstant.pageSize)
        );
        builder.aggregation(catalogAgg);

        // 属性聚合
        // 构建嵌入式聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", EsConstant.ATTRS);
        attrAgg.subAggregation(AggregationBuilders
                .terms("attr_id_agg")
                .field("attrs.attrId")
                .size(EsConstant.pageSize)
                .subAggregation(AggregationBuilders
                        .terms("attr_name_age")
                        .field("attrs.attrName")
//                        .field(EsConstant.Attrs.attrName.toString())
                        .size(1))
                .subAggregation(AggregationBuilders
                        .terms("attr_value_age")
//                        .field(EsConstant.Attrs.attrValue.toString())
                        .field("attrs.attrValue")
                        .size(1))
        );
        builder.aggregation(attrAgg);

        return builder;
    }

    /**
     * 对检索结果 处理、
     *
     * @param searchResponse
     * @param params
     * @return
     */
    private SearchResult searchResultHandler(SearchResponse searchResponse, SearchParams params) {
        SearchResult result = new SearchResult();

        /**
         * 总命中数、当前页码、总页码封装
         */
        long totalHits = searchResponse.getHits().getTotalHits().value;
//        long totalHits = searchResponse.getHits().getTotalHits();
        Integer totalPages =  (int)totalHits %  EsConstant.pageSize == 0 ? (int)totalHits / EsConstant.pageSize : (int)totalHits % EsConstant.pageSize + 1;
        //总记录数
        result.setTotal(totalHits);
        //总页码
        result.setTotalPages(totalPages);
        //页码
        result.setPageNum(params.getPageNum()==null ? 1:params.getPageNum());
        
        /**
         * 命中结果映射封装
         */
        if(totalHits > 0){
            List<SkuEsModel> esModels = new ArrayList<>();
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                String source = hit.getSourceAsString();
                SkuEsModel skuVO = JSON.parseObject(source, SkuEsModel.class);
                if(StringUtils.isNotEmpty(params.getKeyword())){
                    //封装高亮、有时不只有标题设置了高亮
                    for (Map.Entry<String, HighlightField> fieldEntry : hit.getHighlightFields().entrySet()) {
                        String key = fieldEntry.getKey();
                        String value = fieldEntry.getValue().getFragments()[0].toString();
                        if("skuTitle".equalsIgnoreCase(key)){
                            skuVO.setSkuTitle(value);
                        }else {
                            //TODO 都要判断进行映射、或者Switch
                        }
                    }
                }
                esModels.add(skuVO);
            }
            result.setProducts(esModels);
        }

        /**
         * 分类聚合映射封装
         */
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            //获取父聚合分类Id、
            long catalogId = bucket.getKeyAsNumber().longValue();
            //获取子聚合分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();

            //封装
            catalogVos.add(new SearchResult.CatalogVo(catalogId,catalogName));
        }
        result.setCatalogs(catalogVos);

        /**
         *  品牌聚合映射封装
         */
        List<SearchResult.BrandVo>  brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            //获取父聚合品牌名
            long brandId = bucket.getKeyAsNumber().longValue();
            //获取子聚合品牌名
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            //获取子聚合品牌图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_Img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();

            brandVos.add(new SearchResult.BrandVo(brandId,brandName,brandImg));
        }
        result.setBrands(brandVos);

        /**
         * 属性聚合映射封装
         */
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            //属性Id、一个桶唯一
            long attrId = bucket.getKeyAsNumber().longValue();
            //属性名、一个桶唯一
            String attrName = ((ParsedStringTerms) bucket.getAggregations()
                    .get("attr_name_age")).getBuckets()
                    .get(0).getKeyAsString();
            //属性值、可能多个
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations()
                    .get("attr_value_age")).getBuckets()
                    .stream()
                    .map(innBucket -> innBucket.getKeyAsString())
                    .collect(Collectors.toList());


            attrVos.add(new SearchResult.AttrVo(attrId,attrName,attrValues));
        }
        result.setAttrs(attrVos);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        System.out.println("搜索结果：" + result.toString());

        //构建面包屑导航功能
        if (params.getAttrs()!=null && params.getAttrs().size()>0) {
            List<SearchResult.NavVo> collect = params.getAttrs().stream().map(attr -> {
                //分析每一个attrs传过来的查询参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String replace = replaceQueryString(params, attr,"attrs");
                navVo.setLink("http://search.frankguli.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }

        //品牌，分类
        if (params.getBrandId()!=null && params.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();

            navVo.setNavName("品牌");

            R r = productFeignService.brandsInfo(params.getBrandId());
            if (r.getCode() == 0){
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer stringBuffer = new StringBuffer();
                String replace = "";
                for (BrandVo brandVo : brand) {
                    stringBuffer.append(brandVo.getBrandName()+";");
                    replace = replaceQueryString(params, brandVo.getBrandId()+"","brandId");

                }
                navVo.setNavValue(stringBuffer.toString());
                navVo.setLink("http://search.frankguli.com/list.html?" + replace);
            }
            navs.add(navVo);
        }
        //TODO 分类：不需要导航取消（同上）

        return result;
    }

    private String replaceQueryString(SearchParams params, String value,String key) {
        String enCode = null;
        try {
            enCode = URLEncoder.encode(value, "UTF-8");
            enCode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params.get_queryString().replace("&"+key+"=" + enCode, "");
    }
}
